package com.zhaolang.qogir.domain.impl;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.JsonObject;
import com.zhaolang.qogir.bean.ProductBean;
import com.zhaolang.qogir.bean.ProductClassBean;
import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.BaseResp;
import com.zhaolang.qogir.domain.WaresManage;
import com.zhaolang.qogir.server.ClientCallbackImpl;
import com.zhaolang.qogir.server.RadarProxy;
import com.zhaolang.qogir.server.ServerRequestParams;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.Slog;
import com.zhaolang.qogir.util.XUtilsHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WaresManageImpl extends WaresManage {
    private Context context;
    private Handler handler1;
    private Handler handler2;
    private Handler handler3;
    private Handler handler4;
    private Handler handler5;
    private Handler handler6;
    private ServerRequestParams params;

    public WaresManageImpl(Context context) {
        this.context = context;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void updateWaresImageAsync(List<String> imgs, String productId, final BaseCall<UpdateShopResp> call) {
        handler1 = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (call != null && !call.cancel) {
                    call.call((UpdateShopResp) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(writeThumbnailParams(imgs, productId),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        UpdateShopResp resp = new UpdateShopResp();
                        Log.d("Radar", "updateWaresImageAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setMessage(jsonObject2.optString("msg"));
                            resp.setStatus(jsonObject2.optString("status"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler1.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler1.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    /*
     * add product requirement to db
     */
    @SuppressLint("HandlerLeak")
    @Override
    public void updateWaresRequirementsAsync(ProductBeanReq shopBeanReq, final BaseCall<UpdateShopResp> call) {
        handler2 = new Handler() {
            public void handleMessage(Message msg) {
                if (call != null && !call.cancel) {
                    call.call((UpdateShopResp) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(updateWaresRequirementsParams(shopBeanReq),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        UpdateShopResp resp = new UpdateShopResp();
                        Log.d("Radar", "updateWaresRequirementsAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setMessage(jsonObject2.optString("msg"));
                            resp.setStatus(jsonObject2.optString("status"));
                            if (jsonObject2.optString("status").equalsIgnoreCase("success")) {
                                JSONObject jsonObjec3 = new JSONObject(jsonObject2.optString("values"));
                                resp.setProductId(jsonObjec3.optString("product_id"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler2.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler2.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    /**
     * update shop product class
     *
     * @param productClassBeanReq
     * @param call
     */
    @SuppressLint("HandlerLeak")
    @Override
    public void updateShopProductClassAsync(ProductClassBeanReq productClassBeanReq, final BaseCall<BaseResp> call) {
        handler3 = new Handler() {
            public void handleMessage(Message msg) {
                if (call != null && !call.cancel) {
                    call.call((BaseResp) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(updateShopProductClassParams(productClassBeanReq),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        BaseResp resp = new BaseResp();
                        Log.d("Radar", "updateShopProductClassAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setMessage(jsonObject2.optString("msg"));
                            resp.setStatus(jsonObject2.optString("status"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler3.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler3.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    /**
     * Get shop class info from db when reboot
     *
     * @param call
     */
    @SuppressLint("HandlerLeak")
    @Override
    public void getShopClassAsync(final BaseCall<ListProductClassBeanReq> call) {
        handler4 = new Handler() {
            public void handleMessage(Message msg) {
                if (call != null && !call.cancel) {
                    call.call((ListProductClassBeanReq) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(getShopProductClassParams(),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        ListProductClassBeanReq resp = new ListProductClassBeanReq();
                        Log.d("Radar", "getShopClassAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setMessage(jsonObject2.optString("msg"));
                            resp.setStatus(jsonObject2.optString("status"));
                            /* parse product class bean from json object */
                            if (jsonObject2.optString("status").equals("success")) {
                                try {
                                    JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("values"));
                                    int classSize = Integer.parseInt(jsonObject3.optString("class_size"));
                                    String classValues = jsonObject3.optString("class_value");
                                    List<ProductClassBean> listProductClass = new ArrayList<>();
                                    listProductClass.clear();
                                    Object object = new JSONTokener(classValues).nextValue();
                                    if (object instanceof JSONObject) {
                                        ProductClassBean productClassBean = new ProductClassBean();
                                        productClassBean.setProclassClassid(((JSONObject) object).optString("PROCLASS_ID"));
                                        productClassBean.setProclassName(((JSONObject) object).optString("PROCLASS_NAME"));
                                        productClassBean.setProclassShopid(((JSONObject) object).optString("PROCLASS_SHOPID"));
                                        listProductClass.add(productClassBean);
                                    } else if (object instanceof JSONArray) {
                                        // JSON array part
                                        JSONArray jsonArray = (JSONArray) object;
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject details = jsonArray.getJSONObject(i);
                                            ProductClassBean bean = new ProductClassBean();
                                            bean.setProclassShopid(details.optString("PROCLASS_SHOPID"));
                                            bean.setProclassClassid(details.optString("PROCLASS_ID"));
                                            bean.setProclassName(details.optString("PROCLASS_NAME"));
                                            listProductClass.add(bean);
                                        }
                                    }
                                    resp.setBeanListSize(listProductClass.size());
                                    resp.setProclassList(listProductClass);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler4.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler4.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    /**
     * get all product async by shop id
     *
     * @param call
     */
    @SuppressLint("HandlerLeak")
    @Override
    public void getAllProductAsync(final BaseCall<ListProductBeanReq> call) {
        handler5 = new Handler() {
            public void handleMessage(Message msg) {
                if (call != null && !call.cancel) {
                    call.call((ListProductBeanReq) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(getAllProductParams(),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        ListProductBeanReq resp = new ListProductBeanReq();
                        Log.d("Radar", "getAllProductAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setMessage(jsonObject2.optString("msg"));
                            resp.setStatus(jsonObject2.optString("status"));
                            /* parse product class bean from json object */
                            if (jsonObject2.optString("status").equals("success")) {
                                try {
                                    JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("values"));
                                    int classSize = Integer.parseInt(jsonObject3.optString("class_size"));
                                    String classValues = jsonObject3.optString("class_value");
                                    List<ProductBean> listProduct = new ArrayList<>();
                                    listProduct.clear();
                                    Object object = new JSONTokener(classValues).nextValue();
                                    if (object instanceof JSONObject) {
                                        ProductBean bean = new ProductBean();
                                        bean.setProId(((JSONObject) object).optString("PRODUCT_ID"));
                                        bean.setShopId(((JSONObject) object).optString("PRODUCT_SHOPID"));
                                        bean.setPrice(((JSONObject) object).optString("PRODUCT_PRICE"));
                                        bean.setClassId(((JSONObject) object).optString("PRODUCT_CLASSID"));
                                        bean.setThumbnail(((JSONObject) object).optString("PRODUCT_PIC"));
                                        bean.setName(((JSONObject) object).optString("PRODUCT_NAME"));
                                        bean.setDesc(((JSONObject) object).optString("PRODUCT_DESCRIBE"));
                                        bean.setStock(((JSONObject) object).optString("PRODUCT_MONTH_SALE"));
                                        bean.setMaxStock(((JSONObject) object).optString("PRODUCT_TOTAL_SALE"));
                                        bean.setPrice(((JSONObject) object).optString("PRODUCT_PACK_ID"));
                                        bean.setIsOnSale(((JSONObject) object).optBoolean("PRODUCT_IS_ONSALE"));
                                        listProduct.add(bean);
                                    } else if (object instanceof JSONArray) {
                                        // JSON array part
                                        JSONArray jsonArray = (JSONArray) object;
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject details = jsonArray.getJSONObject(i);
                                            ProductBean bean = new ProductBean();
                                            bean.setProId(details.optString("PRODUCT_ID"));
                                            bean.setShopId(details.optString("PRODUCT_SHOPID"));
                                            bean.setPrice(details.optString("PRODUCT_PRICE"));
                                            bean.setThumbnail(details.optString("PRODUCT_PIC"));
                                            bean.setClassId(details.optString("PRODUCT_CLASSID"));
                                            bean.setName(details.optString("PRODUCT_NAME"));
                                            bean.setDesc(details.optString("PRODUCT_DESCRIBE"));
                                            bean.setStock(details.optString("PRODUCT_MONTH_SALE"));
                                            bean.setMaxStock(details.optString("PRODUCT_TOTAL_SALE"));
                                            bean.setPrice(details.optString("PRODUCT_PACK_ID"));
                                            bean.setIsOnSale(details.optBoolean("PRODUCT_IS_ONSALE"));
                                            listProduct.add(bean);
                                        }
                                    }
                                    resp.setBeanListSize(listProduct.size());
                                    resp.setProList(listProduct);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler5.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler5.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    /**
     * get specific product info by product id
     *
     * @param call
     */
    @SuppressLint("HandlerLeak")
    @Override
    public void getProductAsync(String productId, final BaseCall<ProductReq> call) {
        handler6 = new Handler() {
            public void handleMessage(Message msg) {
                if (call != null && !call.cancel) {
                    call.call((ProductReq) msg.obj);
                }
            }
        };
        RadarProxy.getInstance(context).startServerData(getProductParams(productId),
                new ClientCallbackImpl() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject;
                        ProductReq resp = new ProductReq();
                        Log.d("Radar", "getProductAsync: " + result);
                        try {
                            jsonObject = new JSONObject(result);
                            resp.setSuccess(jsonObject.optBoolean("success"));
                            resp.setStatusCode(jsonObject.optInt("statusCode"));
                            JSONObject jsonObject2 = new JSONObject(jsonObject.optString("message"));
                            resp.setMessage(jsonObject2.optString("msg"));
                            resp.setStatus(jsonObject2.optString("status"));
                            /* parse product class bean from json object */
                            if (jsonObject2.optString("status").equals("success")) {
                                JSONObject jsonObject3 = new JSONObject(jsonObject2.optString("values"));
                                String classValues = jsonObject3.optString("class_value");
                                Object object = new JSONTokener(classValues).nextValue();
                                if (object instanceof JSONObject) {
                                    ProductBean bean = new ProductBean();
                                    bean.setProId(((JSONObject) object).optString("PRODUCT_ID"));
                                    bean.setShopId(((JSONObject) object).optString("PRODUCT_SHOPID"));
                                    bean.setPrice(((JSONObject) object).optString("PRODUCT_PRICE"));
                                    bean.setClassId(((JSONObject) object).optString("PRODUCT_CLASSID"));
                                    bean.setThumbnail(((JSONObject) object).optString("PRODUCT_PIC"));
                                    bean.setName(((JSONObject) object).optString("PRODUCT_NAME"));
                                    bean.setDesc(((JSONObject) object).optString("PRODUCT_DESCRIBE"));
                                    bean.setStock(((JSONObject) object).optString("PRODUCT_MONTH_SALE"));
                                    bean.setMaxStock(((JSONObject) object).optString("PRODUCT_TOTAL_SALE"));
                                    bean.setPrice(((JSONObject) object).optString("PRODUCT_PACK_ID"));
                                    resp.setProductBean(bean);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            resp.setStatus("FAILED");
                            Log.d("Radar", "JSONException: " + e);
                        }
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler6.sendMessage(msg);
                    }

                    @Override
                    public void onFailure(String result) {
                        BaseResp resp = new BaseResp();
                        resp.setStatus("FAILED");
                        Message msg = Message.obtain();
                        msg.obj = resp;
                        handler5.sendMessage(msg);
                        System.out.println(result);
                    }
                });
    }

    private ServerRequestParams writeThumbnailParams(List<String> imgs, String productId) {
        Map<String, Object> param = new HashMap<String, Object>();
        params = getServerRequest();
        params.setToken(HttpConstant.TOKEN);
        params.setRequestUrl(HttpConstant.uploadThumbanil(null));
        String userId = SharePreCacheHelper.getUserID(context);
        param.put("SHOP_ID", userId);
        param.put("portrait", imgs);
        param.put("PRODUCT_ID", productId);
        param.put("FKEY", HttpConstant.getFKEY());
        params.setStatus(XUtilsHelper.UPLOAD_FILE_MULTI_PARAM);
        params.setRequestParam(param);
        params.setRequestEntity(null);
        return params;
    }

    /**
     * params setting to get all shop product class
     *
     * @return
     */
    private ServerRequestParams getShopProductClassParams() {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.getShopClass(null));
        String shopId = SharePreCacheHelper.getUserID(context);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("token", HttpConstant.TOKEN);
        param.put("SHOP_ID", shopId);
        param.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(param);
        return params;
    }

    /**
     * params setting to get all shop product class
     *
     * @return
     */
    private ServerRequestParams getAllProductParams() {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.getAllProduct(null));
        String shopId = SharePreCacheHelper.getUserID(context);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("token", HttpConstant.TOKEN);
        param.put("SHOP_ID", shopId);
        param.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(param);
        return params;
    }

    /**
     * update shop product or add shop product
     *
     * @return
     */
    private ServerRequestParams updateWaresRequirementsParams(ProductBeanReq bean) {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.getWriteShopClass(null));
        String shopId = SharePreCacheHelper.getUserID(context);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("token", HttpConstant.TOKEN);
        param.put("SHOP_ID", shopId);
        param.put("PRODUCT_NAME", bean.getName());
        param.put("PRODUCT_PRICE", bean.getPrice());
        param.put("PRODUCT_DESCRIBE", bean.getDesc());
        param.put("PRODUCT_MONTH_SALE", bean.getStock());
        param.put("PRODUCT_TOTAL_SALE", bean.getMaxStock());
        param.put("PRODUCT_CLASSID", bean.getClassId());
        param.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(param);
        return params;
    }

    /**
     * Get target product by product id
     *
     * @param productId
     * @return
     */
    private ServerRequestParams getProductParams(String productId) {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.readProduct(null));
        String shopId = SharePreCacheHelper.getUserID(context);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("token", HttpConstant.TOKEN);
        param.put("SHOP_ID", shopId);
        param.put("PRODUCT_ID", productId);
        param.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(param);
        return params;
    }

    /**
     * update or add shop product class
     *
     * @return
     */
    private ServerRequestParams updateShopProductClassParams(ProductClassBeanReq productClassBeanReq) {
        params = getServerRequest();
        params.setRequestUrl(HttpConstant.writeShopClass(null));
        String shopId = SharePreCacheHelper.getUserID(context);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("token", HttpConstant.TOKEN);
        param.put("PROCLASS_NAME", productClassBeanReq.getProclassName());
        param.put("SHOP_ID", shopId);
        param.put("FKEY", HttpConstant.getFKEY());
        params.setRequestParam(param);
        return params;
    }

    private ServerRequestParams getServerRequest() {
        if (params == null) {
            params = new ServerRequestParams();
        }
        return params;
    }
}
